<?php
declare(strict_types=1);
namespace SixShop\AliyunWuliu\Service;

use SixShop\AliyunWuliu\Entity\ExtensionWuLiuEntity;
use SixShop\AliyunWuliu\Extension;
use SixShop\Core\Contracts\LogisticsInformationResponse;
use SixShop\Core\Contracts\LogisticsInterface;
use think\Model;

class LogisticsService implements LogisticsInterface
{
    public function __construct(private ExtensionWuLiuEntity $extensionWuLiuEntity)
    {
    }

    public function logisticsInformation(string $number, string $type = ''): LogisticsInformationResponse
    {
        $entity = $this->extensionWuLiuEntity->where('number', $number)->when($type, function (Model $query, $type) {
            $query->where('type', $type);
        })->findOrEmpty();
        if (!$entity->isEmpty() && ($entity->is_sign == 1 || strtotime( $entity->update_time) > time() - 600)) {
            // 已签收或10分钟内更新过，直接返回
        } else {
            $entity = $this->extensionWuLiuEntity->queryLogistics($number, $type, $entity);
        }
        return new LogisticsInformationResponse(
            Extension::EXTENSION_ID,
            $entity->number,
            $entity->type,
            $entity->toArray()
        );
    }
}